/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 *
 */
package is202.hrms.web;

import is202.hrms.ejb.ForumEJB;
import is202.hrms.entity.Forum;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
import javax.inject.Named;

/**
 *
 * @author Kim
 */
@Named("forumconverter") @RequestScoped
@FacesConverter(forClass=Forum.class)
public class ForumConverter implements Converter {

    @EJB
    ForumEJB foruEjb;

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        long forumId = Long.parseLong(value);
        if (null == foruEjb) {
            System.out.println("No EJB!");
            throw new ConverterException("No EJB!");
        }
        Forum forum = foruEjb.find(forumId);
        if (null == forum) {
            System.out.println("No value!");
            throw new ConverterException("Cannot convert \""+value+"\" to Forum");
        }
        return forum;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (null != value && value instanceof Forum) {
            Forum forum = (Forum)value;
            return ""+forum.getForumNr();
        }
        throw new ConverterException("Illegal value - must be a Forum object");
    }

}
